package com.shenyue.nbtownlet.util;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

public class CameraUtil {

    public static String openCamera(Activity context, int REQUEST_CODE) throws Exception {
        String state = Environment.getExternalStorageState();
        if (state.equals(Environment.MEDIA_MOUNTED)) {
            StringBuilder sb = new StringBuilder();
            sb.append(Environment.getExternalStorageDirectory())
                    .append(File.separator)
                    .append(Environment.DIRECTORY_DCIM)
                    .append(File.separator)
                    .append("Camera")
                    .append(File.separator);
            String path = sb.toString();
            File file = new File(path);
            if (!file.exists()) {
                file.mkdirs();
            }
            String fileName = getPhotoFileName() + ".jpg";
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            Uri photoUri = Uri.fromFile(new File(path + fileName));
            intent.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
            context.startActivityForResult(intent, REQUEST_CODE);
            return photoUri.getPath();
        }
        return null;
    }

    private static String getPhotoFileName() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        return "IMG0_" + dateFormat.format(new Date());
    }
}
